#include "Utils.h"



//string 转换为time_t  时间格式为2014/03/28 18:25:26
time_t Utils::string2time_t(const string string_time)
{
    tm tm1;
    memset(&tm1, 0, sizeof(tm1));
    time_t time1;

    sscanf(string_time.c_str(), "%d/%d/%d/ %d:%d:%d",
        &(tm1.tm_year),
        &(tm1.tm_mon),
        &(tm1.tm_mday),
        &(tm1.tm_hour),
        &(tm1.tm_min),
        &(tm1.tm_sec));

    tm1.tm_year -= 1900;
    tm1.tm_mon -= 1;

    time1 = mktime(&tm1);

    return time1;

}

//time_t转换为string  时间格式为2014/03/28 18:25:26
string Utils::time_t2string(const time_t time_t_time)
{
    char szTime[100] = {'\0'};

    tm *pTm = new tm;
   // localtime_s(pTm, &time_t_time);
    pTm = localtime(&time_t_time);
    pTm->tm_year += 1900;
    pTm->tm_mon +=1;

    snprintf(szTime, sizeof(szTime), "%04d/%02d/%02d %02d:%02d:%02d",
        pTm->tm_year,
        pTm->tm_mon,
        pTm->tm_mday,
        pTm->tm_hour,
        pTm->tm_min,
        pTm->tm_sec);

    string strTime = szTime;

    delete pTm;
    pTm = NULL;

    return strTime;
}

string Utils::time_t2str(const time_t time_t_time)
{
    char szTime[128] = {0};

    tm *pTm;
    pTm = localtime(&time_t_time);
    pTm->tm_year += 1900;
    pTm->tm_mon +=1;
    
    strftime(szTime,64,"%Y%m%d%H%M%S", pTm);

    string strTime = szTime;
   
    return strTime;
}

long Utils::getCurTime()
{
   time_t myt=time(NULL);
   return myt;
}

//字符串分割函数
vector<std::string> Utils::split(std::string str,std::string pattern)
{
  std::string::size_type pos;
  vector<std::string> result;
  str+=pattern;//扩展字符串以方便操作
  int size=str.size();

  for(int i=0; i<size; i++)
  {
    pos=str.find(pattern,i);
    if(pos<size)
    {
      std::string s=str.substr(i,pos-i);
      result.push_back(s);
      i=pos+pattern.size()-1;
    }
  }
  return result;
}

void Utils::writeFile(string filename, char *data, int fsize)
{
   FILE *fp = NULL;
   fp = fopen(filename.c_str(), "w");
    if( fp == NULL ) {
        perror("fopen error");
        
        return;
    }
   int size2 = 0, nodeSize;
   while( size2 < fsize ) {
     if( (nodeSize = fwrite(data + size2, 1, fsize - size2, fp) ) < 0 ) {
         perror("write file fail");
         fclose(fp);
        return;
     }
     std:cout<< "nodeSize=="<< nodeSize <<endl;
     size2 += nodeSize;       
    }
  fclose(fp);
}
